package com.jolink.omiis.wechat.broker;

import java.io.IOException;
import java.io.StringReader;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.jolink.omiis.wechat.WeChatContext;
import com.jolink.omiis.wechat.api.IWeChatBrokerMessage;
import com.jolink.omiis.wechat.outer.AbstractWeChatController;
import com.jolink.omiis.wechat.outer.BrokerMessageWorker;
import com.jolink.omiis.wechat.util.XmlParser;

/**
 * 开放平台微信中继Server 目前暂为拍拍贷支持该服务 1、拍拍贷消息明文传送 2、消息采用异步处理 3、微信用户发送的消息全部发送到全媒体-微信后台
 * 
 * @author WangYanqing
 *
 */
@Controller
@RequestMapping("/wechat/broker/receive")
@Deprecated
public class WechatMessageBrokerController extends AbstractWeChatController {

	private static Logger logger = LoggerFactory.getLogger(WechatMessageBrokerController.class);

	@Autowired
	private ThreadPoolTaskExecutor taskExecutor;

	@Autowired
	private WeChatContext context;

	@Autowired
	private IWeChatBrokerMessage broker;

	@RequestMapping(method = RequestMethod.GET)
	public void get(HttpServletRequest request, HttpServletResponse response) {
		logger.info("接收到腾讯中继服务器普通信息请求：{}，InstanceId：{}", request.getParameterMap(), this.hashCode());
		try {
			String body = readBody(request);
			if (StringUtils.isEmpty(body)) {
				throw new RuntimeException("信息为空！");
			}
			logger.info("请求信息：{}", body);
			StringReader sr = new StringReader(body);
			Document doc = XmlParser.str2Xml(sr);
			logger.info("transfer2Xml={}", doc.asXML());
			String ret = "success";
			logger.info("响应服务器内容：{}", ret);
			response.getWriter().write(ret);
			response.getWriter().flush();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			try {
				response.getWriter().write("");
			} catch (IOException e1) {
				logger.error(e.getMessage(), e);
			}
			return;
		}
	}

	@RequestMapping(method = RequestMethod.POST)
	public void post(HttpServletRequest request, HttpServletResponse response) {
		long t1 = System.currentTimeMillis();
		logger.info("接收到腾讯中继服务器普通信息请求：{}，InstanceId：{}，CharacterEncoding：{}", request.getParameterMap(),
				this.hashCode(), request.getCharacterEncoding());
		String requestBody = null;
		String responseMessage = "success";
		try {
			response.setHeader("Cache-Control", "no-cache");
			response.setHeader("Prama", "no-cache");
			response.setContentType("text/xml;charset=UTF-8");
			response.setCharacterEncoding("UTF-8");
			requestBody = readBody(request);
			if (StringUtils.isEmpty(requestBody)) {
				throw new RuntimeException("腾讯微信用户发送信息为空！");
			}
			// String decryptMsg = decrypt(request.getParameterMap(),
			// requestBody);
			logger.info("开始异步处理微信请求，请求内容：{}。", requestBody);
			// IMessageHandler messageHandler =
			// createMessageHandler(request.getParameterMap(), requestBody);
			// wr = messageHandler.handleMessage();
			// logger.info("请求信息处理完成，返回内容：{}。", GsonUtil.obj2Json(wr));
			// logger.info("返回处理结果：{}", wr.getResponseMsg());
			// if (!isReleaseTest || isSync) {
			// taskExecutor.execute(new MessageWorker(context,
			// request.getParameterMap(), requestBody, messager));
			// }
			taskExecutor.execute(new BrokerMessageWorker(context, request.getParameterMap(), requestBody, broker));
			response.getWriter().write(responseMessage);
			response.flushBuffer();
			response.getWriter().flush();
			response.getWriter().close();
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
			try {
				response.getWriter().write("");
			} catch (IOException e1) {
				logger.error(e.getMessage(), e);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			try {
				response.getWriter().write("");
			} catch (IOException e1) {
				logger.error(e.getMessage(), e);
			}
		}
		long t2 = System.currentTimeMillis();
		logger.info("处理腾讯中继服务器普通信息请求完成，耗时：{}毫秒。", (t2 - t1));
	}
}
